/*
 * @Author: intellectual-seeker 3336339701@qq.com
 * @Date: 2025-09-10 06:37:41
 * @LastEditors: intellectual-seeker 3336339701@qq.com
 * @LastEditTime: 2025-09-10 21:28:20
 * @FilePath: /code/lesson33/cp_ringqueue/Main.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
using namespace std;
#include "RingQueue.hpp"
#include "Thread.hpp"
using namespace ThreadModule;
#include <string>
#include <unistd.h>
#include "Task.hpp"

using ringqueue_t = RingQueue<task_t>;

void ProductorRun(ringqueue_t& rq, string name)
{
    while(true)
    {
        rq.Enqueue(download);
        cout << name << " is producted" << endl;
    }
}

void ConsumerRun(ringqueue_t& rq, string name)
{
    while(true)
    {
        sleep(1);
        task_t task;
        rq.Pop(&task);
        cout << name << " get : "; 
        task();//bad_function_call: 尝试调用没有目标的function对象时会出现此异常
    }
}

void InitComm(vector<Thread<ringqueue_t>>& threads, ringqueue_t& rq, int num, func_t<ringqueue_t> func, string who)
{
    for(int i = 0; i < num; i++)
    {
        string name = who + '-' + to_string(i + 1);
        threads.emplace_back(func, rq, name);
    }
}

void InitProductor(vector<Thread<ringqueue_t>>& threads, ringqueue_t& rq, int num)
{
    InitComm(threads, rq, num, ProductorRun, "productor");
}

void InitConsumer(vector<Thread<ringqueue_t>>& threads, ringqueue_t& rq, int num)
{
    InitComm(threads, rq, num, ConsumerRun, "consumer");
}

void StartAll(vector<Thread<ringqueue_t>>& threads)//vector必须用引用，存储线程tid
{
    for(auto& thread : threads)
    {
        thread.start();
    }
}

void WaitAllThread(vector<Thread<ringqueue_t>> threads)//尝试用拷贝对象是否能够正常回收进程
{
    for(auto thread : threads)
    {
        thread.join();
    }
}

int main()
{
    ringqueue_t rq(5);
    vector<Thread<ringqueue_t>> threads;
    InitProductor(threads, rq, 3);
    InitConsumer(threads, rq, 2);
    StartAll(threads);
    WaitAllThread(threads);

    return 0;
}